{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "view-in-github"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/jeffvestal/ElasticDocs_GPT/blob/main/load_embedding_model.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "6xoLDtS_6Df1"
   },
   "source": [
    "# ElasticDocs GPT Blog\n",
    "# Loading an embedding from Hugging Face into Elasticsearch\n",
    "\n",
    "This code will show you how to load a supported embedding model from Hugging Face into an elasticsearch cluster in [Elastic Cloud](https://cloud.elastic.co/)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "DgxCKQS7mCZw"
   },
   "source": [
    "# Setup\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "Ly1f1P-l9ri8"
   },
   "source": [
    "## Install and import required python libraries"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "MJAb_8zlPFhQ"
   },
   "source": [
    "Elastic uses the [eland python library](https://github.com/elastic/eland) to download modesl from Hugging Face hub and load them into elasticsearch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "rUedSzQW9FIF"
   },
   "outputs": [],
   "source": [
    "pip -q install eland elasticsearch sentence_transformers transformers torch==1.11"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "wyUZXUi4RWWL"
   },
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "from eland.ml.pytorch import PyTorchModel\n",
    "from eland.ml.pytorch.transformers import TransformerModel\n",
    "from elasticsearch import Elasticsearch\n",
    "from elasticsearch.client import MlClient\n",
    "\n",
    "import getpass"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "r7nMIbHke37Q"
   },
   "source": [
    "## Configure elasticsearch authentication. \n",
    "The recommended authentication approach is using the [Elastic Cloud ID](https://www.elastic.co/guide/en/cloud/current/ec-cloud-id.html) and a [cluster level API key](https://www.elastic.co/guide/en/kibana/current/api-keys.html)\n",
    "\n",
    "You can use any method you wish to set the required credentials. We are using getpass in this example to prompt for credentials to avoide storing them in github."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "SSGgYHome69o"
   },
   "outputs": [],
   "source": [
    "es_cloud_id = getpass.getpass(\"Enter Elastic Cloud ID:  \")\n",
    "es_user = getpass.getpass(\"Enter cluster username:  \")\n",
    "es_pass = getpass.getpass(\"Enter cluster password:  \")\n",
    "\n",
    "# es_api_id = getpass.getpass('Enter cluster API key ID:  ')\n",
    "# es_api_key = getpass.getpass('Enter cluster API key:  ')"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "jL4VDnVp96lf"
   },
   "source": [
    "## Connect to Elastic Cloud"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "I8mVJkKmetXo"
   },
   "outputs": [],
   "source": [
    "# es = Elasticsearch(cloud_id=es_cloud_id,\n",
    "#                   api_key=(es_api_id, es_api_key)\n",
    "#                   )\n",
    "es = Elasticsearch(cloud_id=es_cloud_id, basic_auth=(es_user, es_pass))\n",
    "es.info()  # should return cluster info"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "uBMWHj-ZmtvE"
   },
   "source": [
    "# Load the model From Hugging Face into Elasticsearch\n",
    "Here we specify the model id from Hugging Face. The easiest way to get this id is clicking the copy the model name icon next to the name on the model page. \n",
    "\n",
    "When calling `TransformerModel` you specify the HF model id and the task type. You can try specifying `auto` and eland will attempt to determine the correct type from info in the model config. This is not always possible so a list of specific `task_type` values can be viewed in the following code: \n",
    "[Supported values](https://github.com/elastic/eland/blob/15a300728876022b206161d71055c67b500a0192/eland/ml/pytorch/transformers.py#*L41*)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "zPV3oFsKiYFL"
   },
   "outputs": [],
   "source": [
    "# Set the model name from Hugging Face and task type\n",
    "hf_model_id = \"sentence-transformers/all-distilroberta-v1\"\n",
    "tm = TransformerModel(hf_model_id, \"text_embedding\")\n",
    "\n",
    "# set the modelID as it is named in Elasticsearch\n",
    "es_model_id = tm.elasticsearch_model_id()\n",
    "\n",
    "# Download the model from Hugging Face\n",
    "tmp_path = \"models\"\n",
    "Path(tmp_path).mkdir(parents=True, exist_ok=True)\n",
    "model_path, config, vocab_path = tm.save(tmp_path)\n",
    "\n",
    "# Load the model into Elasticsearch\n",
    "ptm = PyTorchModel(es, es_model_id)\n",
    "ptm.import_model(\n",
    "    model_path=model_path, config_path=None, vocab_path=vocab_path, config=config\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "4UYSzFp3vHdB"
   },
   "source": [
    "# Starting the Model"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "wQwfozwznK4Y"
   },
   "source": [
    "## View information about the model\n",
    "This is not required but can be handy to get a model overivew"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "b4Wv8EJvpfZI"
   },
   "outputs": [],
   "source": [
    "# List the in elasticsearch\n",
    "m = MlClient.get_trained_models(es, model_id=es_model_id)\n",
    "m.body"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "oMGw3sk-pbaN"
   },
   "source": [
    "## Deploy the model\n",
    "This will load the model on the ML nodes and start the process(es) making it available for the NLP task"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "w5muJ1rLqvUW"
   },
   "outputs": [],
   "source": [
    "s = MlClient.start_trained_model_deployment(es, model_id=es_model_id)\n",
    "s.body"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "id": "ZytlELrsnn_O"
   },
   "source": [
    "## Verify the model started without issue\n",
    "Should output -> {'routing_state': 'started'}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ZaQUUWe0Hxwz"
   },
   "outputs": [],
   "source": [
    "stats = MlClient.get_trained_models_stats(es, model_id=es_model_id)\n",
    "stats.body[\"trained_model_stats\"][0][\"deployment_stats\"][\"nodes\"][0][\"routing_state\"]"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "include_colab_link": true,
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
